package com.xf.protocol;

import com.xf.common.Invocation;
import com.xf.rigister.LocalRigister;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServerHandler_rig_pro implements Runnable{
    private ServerSocket serverSocket;

    public HttpServerHandler_rig_pro(ServerSocket serverSocket) {
        this.serverSocket = serverSocket;
    }

    public void run() {
        //System.out.println("New con connected");
        Object result = null;
        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.out.println("与注册中心连接失败！");
        }
        System.out.println("收到客户端请求");
        System.out.println("处理请求中。。。");
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream inputStream = null;
        Invocation invocation = null;
        try {
            inputStream = new ObjectInputStream(clientSocket.getInputStream());
            invocation = (Invocation) inputStream.readObject();
        } catch (IOException |ClassNotFoundException e) {
            System.out.println("读取客户端请求时发生错误！");
        }

        String string = invocation.getInterfaceName() + invocation.getVersion();
        if(!string.startsWith("com.xf")) string="com.xf."+string;

        Class classImpl=null;
        Method method = null;
        if(LocalRigister.is_exist(string)) {
            classImpl = LocalRigister.get(string);
            try {
                method = classImpl.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            } catch (NoSuchMethodException e) {
                System.out.println("找不到要调用的函数");
                result="找不到要调用的函数: "+invocation.getMethod();
            }
        }
        else result="找不到该服务: "+string;



        try {
            result = method.invoke(classImpl.newInstance(), invocation.getParameters());
        } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
            System.out.println("调用本地服务失败！");
        }

        try {
            objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
            objectOutputStream.writeObject(result);
            System.out.println("处理结果已返回客户端。");
        } catch (IOException e) {
            System.out.println("返回处理结果时发生错误");
        }

    }
}
